package com.itheima.cookie;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/*
当浏览器再次访问的时候 浏览器会自动带着跟我当前项目相关cookie过来
  所以我们在这里要进行获取cookie解析cookie

  获取浏览器携带的cookie
 */
@WebServlet("/get")
public class GetCookieServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("我们服务器获取一下浏览器带过来的cookie");
        //方法很 简单 带过来的cookie请求中
        Cookie[] cookies = request.getCookies();//因为可能有多个cookie

        if(cookies!=null&&cookies.length>0){//健壮性校验 保证遍历的容器有内容

            for (Cookie cookie : cookies) {
                //解析cookie
                String name = cookie.getName();
                String value = cookie.getValue();
                System.out.println("当前cookie名字:"+name+" 值:"+value);
            }

        }

        response.setContentType("text/html;charset=utf-8");
        response.getWriter().write("服务器已经把浏览器带过来的cookie解析完了");
    }
}
